package com.j3.sql;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.j3.db.ConnectionManager;
import com.j3.db.Db;

public class DBMetaDataUtils {
	
	public static List<String> getColumns(Db db, String tableName) throws SQLException {
		Connection conn = null;
		try {
			conn = ConnectionManager.getConn(db);
			DatabaseMetaData metaData = conn.getMetaData();
			ResultSet rs = metaData.getColumns(null, null, tableName, null);
			List<String> columns = new ArrayList<String>();
			while(rs.next()) {
				columns.add(rs.getString("COLUMN_NAME"));
			}
			return columns;
		}finally {
			ConnectionManager.close(conn);
		}
	}
	
	public static boolean checkIfTableExists(Db db, String tableName) throws SQLException {
		Connection conn = null;
		try {
			conn = ConnectionManager.getConn(db);
			DatabaseMetaData metaData = conn.getMetaData();
			ResultSet rs = metaData.getColumns(null, null, tableName, null);
			if(rs.next()) {
				return true;
			}
			return false;
		}finally {
			ConnectionManager.close(conn);
		}
	}
}
